using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using System.Collections.Generic;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_ChooseGiftHeroPanel : UIBaseNode
    {
        #region Template Generate,don't modify
        protected class UIB_UIN_ChooseGiftHeroPanel
        {
            #region ObjectBinding Generate
            public IQIGame.Onigao.Framework.ExText textTitle { protected set; get; }
            public UnityEngine.UI.ExLoopVerticalScrollRect scrollArea { protected set; get; }
            public UnityEngine.GameObject slider { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnSure { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnCancel { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textTitle", out var __tbv0);
                this.textTitle = __tbv0;
                __binding.TryGetVariableValue<UnityEngine.UI.ExLoopVerticalScrollRect>("scrollArea", out var __tbv1);
                this.scrollArea = __tbv1;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("slider", out var __tbv2);
                this.slider = __tbv2;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnSure", out var __tbv3);
                this.btnSure = __tbv3;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnCancel", out var __tbv4);
                this.btnCancel = __tbv4;
            }
            #endregion ObjectBinding Generate 
        }
        #endregion Template Generate,don't modify

        #region fields
        private LoopScrollAdapter<UIN_ChooseGiftHeroCell> chooseCells;
        private UIN_ChooseGiftSlider slider;

        private ItemData itemData;
        private CfgSystemEffect cfgItemEffect;
        private IReadOnlyList<int> cellList;
        private int maxChooseNum = 1;

        private List<int> chooseKeys = ListPool<int>.Get();
        private int useNum = 1;
        #endregion fields

        #region properties

        protected UIB_UIN_ChooseGiftHeroPanel ui { get; set; }
        protected UIMsgDispatcher uiMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;

        #endregion properties

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_ChooseGiftHeroPanel();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {
            this.chooseCells = this.InitLoopScroll<UIN_ChooseGiftHeroCell>(this.ui.scrollArea, this.OnChooseCellChanged);
            this.chooseCells.InitUnitSelected(UnitSelectType.ByExButton, this.OnChooseCellSelected, this.OnChooseCellUnSelecte);
            this.slider = this.InitChildNode<UIN_ChooseGiftSlider>(this.ui.slider);
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        /// <summary>
        /// 添加UGUI侦听
        /// </summary>
        protected override void AddUGUIListener()
        {
            this.ui.btnCancel.onClick.AddListener(this.OnClickBtnCancel);
            this.ui.btnSure.onClick.AddListener(this.OnClickBtnSure);
        }

        /// <summary>
        /// 添加全局侦听（MsgDispatcher）
        /// </summary>
        protected override void AddMsgListeners()
        {

        }

        protected override void OnDispose()
        {

        }

        #region methonds
        public void Show(ItemData itemData)
        {
            this.SetData(itemData);
            this.Show();
            this.ShowTitle();
            this.ShowList();
            this.ShowSlider();
        }

        private void SetData(ItemData itemData)
        {
            this.itemData = itemData;
            var cfgEffect = TableCenter.systemEffect.Get(itemData.cfgData.ItemEffectID);
            this.cfgItemEffect = cfgEffect;
            this.maxChooseNum = cfgEffect.Params[0];
            this.cellList = cfgEffect.ExtraParams;
        }

        private void ShowTitle()
        {
            this.ui.textTitle.text = APIUIChooseGift.GetChooseHeroTitle(this.maxChooseNum);
        }

        private void ShowList()
        {
            this.chooseCells.SetUnitMitiSelect(this.maxChooseNum, this.OnCallFullWhenSelectOtherCell);
            var cnt = this.cellList.Count / APIUIConst.CostDefaultSpacing;
            this.chooseCells.RefillCells(cnt);
        }

        private void OnCallFullWhenSelectOtherCell()
        {
            NoticeModule.ShowNoticeNoCall(APIUIChooseGift.NoticeCid_ChooseFull);
        }

        private void OnChooseCellChanged(UIN_ChooseGiftHeroCell item, int index)
        {
            int key = GetListDataIndex(index);
            int itemCid = this.cellList[key];
            int itemNum = this.cellList[key + 1];
            item.Show(itemCid, itemNum);
            this.RefreshChooseCellSelecteState(item, index);
        }

        private void RefreshChooseCellSelecteState(UIN_ChooseGiftHeroCell item, int dataKey)
        {
            bool isSelected = this.IsSelectedCellData(dataKey);
            item.SetSelected(isSelected, this.maxChooseNum <= 1);
        }

        private bool IsSelectedCellData(int dataKey)
        {
            return (dataKey >= 0 && this.chooseKeys.Contains(dataKey));
        }

        private int GetListDataIndex(int cellIndex)
        {
            return cellIndex * APIUIConst.CostDefaultSpacing;
        }

        private void OnChooseCellSelected(int index, UIN_ChooseGiftHeroCell item)
        {
            this.AddSelectedData(index);
            this.RefreshChooseCellSelecteState(item, index);
        }

        private void AddSelectedData(int dataKey)
        {
            if (dataKey < 0)
                return;
            if (!this.chooseKeys.Contains(dataKey))
                this.chooseKeys.Add(dataKey);
        }

        private void OnChooseCellUnSelecte(int index, UIN_ChooseGiftHeroCell item)
        {
            this.RemoveSelectedData(index);
            this.RefreshChooseCellSelecteState(item, index);
        }

        private void RemoveSelectedData(int dataKey)
        {
            if (dataKey < 0)
                return;
            this.chooseKeys.Remove(dataKey);
        }

        private void ShowSlider()
        {
            int nMax = ItemModule.Instance.GetCanUseMaxNum(this.itemData);
            var ud = NumerCappedRange.NewFromPool().Sync(1, nMax, 1);
            this.slider.Show(APIUIChooseGift.FmtItemUseNum, ud, this.OnSliderNumChanged);
        }

        private void OnSliderNumChanged(NumerCappedRange udNum)
        {
            this.useNum = udNum.currentIntValue;
        }

        private void OnClickBtnCancel()
        {
            this.Close();
        }

        private void OnClickBtnSure()
        {
            if (this.chooseKeys.Count < this.maxChooseNum)
            {
                NoticeModule.ShowNoticeNoCall(APIUIChooseGift.NoticeCid_NoChoose);
                return;
            }

            this.SendChooseGift().Forget();
        }

        private async UniTaskVoid SendChooseGift()
        {
            var result = await ItemModule.CS_useItem(this.itemData.id, this.itemData.cid, this.useNum, this.chooseKeys);
            if (result.IsSuccess)
            {
                ItemModule.Instance.UpItemCdInfo(result.result.itemCdInfo);
                NoticeModule.ShowUIItemGet(result.result.addItems);
                this.Close();
            }
        }
        #endregion methonds
    }
}
